/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.conner.command_line;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.LinkedList;
/**
 *
 * @author leanrobot
 */
public class CommandLineParser
{
    protected HashMap<String,Method> parameters;
    
    protected boolean backupFiles = false;
    protected boolean noAct = false;
    protected boolean help = false;
    protected boolean filesSpecified=false;
    protected boolean fixAll = false;
    protected String[] files;
    
    protected static final String helpString = "This is the help String";
    public CommandLineParser(String sArgs) throws Exception
    {
	parameters = new HashMap<String,Method>();
	declareArguments();
	parseArguments(sArgs);
    }
    
    public void declareArguments() throws Exception
    {
	parameters.put("-backup",this.getClass().getMethod("backupMethod"));
	parameters.put("-files",this.getClass().getMethod("filesMethod"));
	parameters.put("-fix-all",this.getClass().getMethod("fixAllMethod"));
	parameters.put("help", this.getClass().getMethod("helpMethod"));
	parameters.put("-no-act", this.getClass().getMethod("noActMethod"));
	
    }
    
    public void parseArguments(String sArgs) throws Exception
    {
	//TODO: Add code which checks for special cases, such as when the user has quotations to specify a file with multiple word names
	//TODO: add error checking for parsing arguments
	String[] args = sArgs.split("\\s");
	for(int i=0; i<args.length;)
	{
	    i=((Integer)(parameters.get(args[i]).invoke(args, new Integer(i)))).intValue();
	}
	
    }
    
    protected Integer backupMethod(String[] args, Integer index)
    {
	backupFiles=true;
	return index += 1;
    }
    public boolean isBackup()
    {
	return backupFiles;
    }
    
    protected Integer noActMethod(String[] args, Integer index)
    {
	noAct=true;
	return index+=1;
    }
    public boolean isNoAct()
    {
	return noAct;
    }
    
    protected Integer helpMethod(String[] args, Integer index)
    {
	help=true;
	return new Integer(args.length+1);
    }
    public boolean isHelp()
    {
	return help;
    }
    public String getHelpString()
    {
	return helpString;
    }
    
    protected Integer fixAllMethod(String[] args, Integer index)
    {
	fixAll=true;
	return index+=1;
    }
    public boolean isFixAll()
    {
	return fixAll;
    }
    
    protected Integer filesMethod(String[] args, Integer indexInteger)
    {
	int index = indexInteger.intValue(); //convenience variable for operations
	LinkedList<String> fileList = new LinkedList<String>();
	if(args[index].equals("-files"))
	{
	    index+=1;
	    while(!args[index].startsWith("-"))
	    {
		fileList.add(args[index]);
	    }
	    files = fileList.toArray(new String[fileList.size()]);
	}
	return new Integer(index);
    }
    public String[] getFiles()
    {
	return files;
    }
    
    public static void main(String[] args)
    {
	
    }
}
